package com.lkj;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.swing.clipboard.ClipboardUtil;
import cn.hutool.json.JSONUtil;
import com.baidu.aip.face.AipFace;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Simple {

    //设置APPID/AK/SK
    public static final String APP_ID = "22424249";
    public static final String API_KEY = "PsSm8fEG7D9qSG0DXgpjYUCV";
    public static final String SECRET_KEY = "DHOHP3RG6PlogUaOv7imMGi3hUHkRcV6";

    public static void main(String[] args) {

//        AipFace client = new AipFace(APP_ID,API_KEY,SECRET_KEY);
//
//        client.setConnectionTimeoutInMillis(2000);
//        client.setSocketTimeoutInMillis(60000);

//        client.setHttpProxy();

//        String auth = getAuth(API_KEY, SECRET_KEY);
//        System.out.println(auth);
//        String faceDetect = faceDetect();
//        System.out.println("faceDetect:"+faceDetect);

//        String add = add();
//        System.out.println("add:"+add);
        String faceMatch = faceMatch();
        System.out.println(faceMatch);
    }


    public static String faceMatch() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
        try {

            Map<String,Object> map = new HashMap<>();
            map.put("image",getImage("lkj.jpg"));
            map.put("image_type","BASE64");
            map.put("face_type","LIVE");
            map.put("quality_control","LOW");
            map.put("liveness_control","NONE");

            Map<String,Object> map1 = new HashMap<>();
            map1.put("image",getImage("likj.jpg"));
            map1.put("image_type","BASE64");
            map1.put("face_type","LIVE");
            map1.put("quality_control","LOW");
            map1.put("liveness_control","NONE");

            List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
            list.add(map);
            list.add(map1);

            String param = JSONUtil.toJsonStr(list);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth(API_KEY,SECRET_KEY);

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String add() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";


        try {
            String image = getImage();

            Map<String, Object> map = new HashMap<>();
            map.put("image",image);
            map.put("group_id", "heyuan");
            map.put("user_id", "lkj");
            map.put("user_info", "likj");
            map.put("liveness_control", "NONE");
            map.put("image_type", "BASE64");
            map.put("quality_control", "HIGH");

            String param = JSONUtil.toJsonStr(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth(API_KEY,SECRET_KEY);

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String faceDetect(){
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
        try {
            Map<String, Object> map = new HashMap<>();

            String image = getImage();

            map.put("image",image);
            map.put("face_field", "faceshape,facetype");
            map.put("image_type", "BASE64");

            String param = JSONUtil.toJsonStr(map);


            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth(API_KEY, SECRET_KEY);

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAuth(String apiKey,String secretKey){

        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + apiKey
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + secretKey;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }
    public static String getImage() throws IOException {

        File file = new File("F:\\java\\gather\\baidu-face\\iamges\\lkj.jpg");

        String encode = Base64.encode(file);

        ClipboardUtil.setStr(encode);

        System.out.println(encode);
        return encode;
    }

    public static String getImage(String fileName) throws IOException {

        String filePath = "F:\\java\\gather\\baidu-face\\iamges\\"+fileName;

        File file = new File(filePath);

        String encode = Base64.encode(file);

        ClipboardUtil.setStr(encode);

        System.out.println(encode);
        return encode;
    }
}
